package com.ddtech.business.course.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ddtech.business.common.BaseService;
import com.ddtech.business.constant.BusinessEnum;
import com.ddtech.business.constant.Del;
import com.ddtech.business.course.entity.Course;
import com.ddtech.business.course.entity.CourseType;
import com.ddtech.business.course.mapper.CourseTypeMapper;
import com.ddtech.business.course.query.CourseTypeQuery;
import com.ddtech.business.course.service.CourseService;
import com.ddtech.business.course.service.CourseTypeService;
import com.ddtech.business.course.vo.res.CourseTypeTreeVo;
import com.ddtech.exception.BizPreconditions;
import com.ddtech.utils.PageUtil;
import com.ddtech.utils.TreeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类表 服务实现类
 * </p>
 *
 * @author bin_pu
 * @since 2023-02-06
 */
@Service
public class CourseTypeServiceImpl extends BaseService<CourseTypeMapper, CourseType> implements CourseTypeService {
    @Autowired
    private CourseService courseService;

    @Override
    public Object pageList(CourseTypeQuery courseTypeQuery) {
        IPage page = this.page(courseTypeQuery.populatePage(), courseTypeQuery.autoWrapper());
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    @Override
    public void create(CourseType courseType) {
        courseType.init();
        this.saveOrUpdate(courseType);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(String id) {
        CourseType courseType = this.getById(id);
        BizPreconditions.check(courseType == null, BusinessEnum.QUERY_ERROR.getMsg());
        List<String> ids = new ArrayList<>();
        ids.add(courseType.getId());
        Set<CourseType> courseTypeSet = new HashSet<>();
        findSubType(ids, courseTypeSet);
        courseTypeSet.forEach(item -> {
            LambdaQueryWrapper<Course> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(Course::getTypeId,item.getId());
            queryWrapper.eq(Course::getIsDelete, Del.FALSE.getStatus());
            int count = courseService.count(queryWrapper);
            BizPreconditions.check(count>0,item.getLabel()+"关联课程信息无法删除！");
            item.baseDelete();
            this.saveOrUpdate(item);
        });
    }

    @Override
    public Object getTree(CourseTypeQuery courseTypeQuery) {
        List<CourseType> courseTypeList = this.list(courseTypeQuery.autoWrapper());
        List<CourseTypeTreeVo> data = courseTypeList.stream().map(map -> JSON.parseObject(JSON.toJSONString(map), CourseTypeTreeVo.class))
                .sorted(Comparator.comparing(CourseTypeTreeVo::getSort, Comparator.nullsFirst(Comparator.naturalOrder())))
                .collect(Collectors.toList());
        if(courseTypeQuery.getIsPage()==1){
            List<CourseTypeTreeVo> treeData = TreeUtils.buildListToTree(data);
            List list = PageUtil.toPage(courseTypeQuery.getPage() - 1, courseTypeQuery.getSize(), treeData);
            return PageUtil.toPage(list, treeData.size());
        }
        return TreeUtils.buildListToTree(data);
    }

    public void findSubType(List<String> ids, Set<CourseType> courseTypeSet) {
        for (String id : ids) {
            CourseTypeQuery orgQuery = new CourseTypeQuery();
            orgQuery.setPid(id);
            List<CourseType> list = this.list(orgQuery.autoWrapper());
            if (CollUtil.isNotEmpty(list)) {
                List<String> collect = list.stream().map(CourseType::getId).collect(Collectors.toList());
                findSubType(collect, courseTypeSet);
            }
            courseTypeSet.add(this.getById(id));
        }
    }

}
